import { Injectable } from '@nestjs/common';
import { CreateOrderDto } from './dto/create-order.dto';
import { UpdateOrderDto } from './dto/update-order.dto';
import { Order } from './entities/order.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Car } from '../car/entities/car.entity';
import { User } from '../user/entities/user.entity';
import { Service } from '../service/entities/service.entity';

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
    @InjectRepository(Car)
    private readonly carRepository: Repository<Car>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Service)
    private readonly serviceRepository: Repository<Service>,
  ) {}

  // 创建一个订单
  async create(createOrderDto: CreateOrderDto) {
    const user = await this.userRepository.findOne({
      where: { id: createOrderDto.userId },
    });
    const service = await this.serviceRepository.findOne({
      where: { id: createOrderDto.serviceId },
    });
    const car = await this.carRepository.findOne({
      where: { id: createOrderDto.carId },
    });

    const order = new Order();
    order.user = user;
    order.service = service;
    order.car = car;

    return await this.orderRepository.save(order);
  }

  async findAll(): Promise<Order | any> {
    return await this.orderRepository.find();
  }

  // 分页查询管理员地区的订单
  async skipFind(
    currentPage: number,
    pageSize: number,
    city: string,
    keywords?: string,
  ): Promise<Array<Order> | any> {
    let list = null;
    if (keywords) {
      list = await this.orderRepository
        .createQueryBuilder('order')
        .leftJoinAndSelect('order.user', 'user')
        .leftJoinAndSelect('order.car', 'car')
        .leftJoinAndSelect('order.service', 'service')
        .where('user.city = :city', { city: city })
        .andWhere('order.isDelete = :isDelete', { isDelete: false })
        .andWhere('service.description LIKE :description', {
          description: `%${keywords}%`,
        })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    } else {
      list = await this.orderRepository
        .createQueryBuilder('order')
        .leftJoinAndSelect('order.user', 'user')
        .leftJoinAndSelect('order.car', 'car')
        .leftJoinAndSelect('order.service', 'service')
        .where('user.city = :city', { city: city })
        .andWhere('order.isDelete = :isDelete', { isDelete: false })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    }
    return {
      list: list[0],
      total: list[1],
      pageSize,
      currentPage,
      pages: Math.ceil(list[1] / pageSize),
    };
  }

  async findOne(id: number): Promise<Order | any> {
    return await this.orderRepository.findOne({
      relations: ['user', 'service', 'car', 'car.photos', 'service.photos'],
      where: { id },
    });
  }

  async update(id: number, params: any) {
    const order = await this.orderRepository.findOne({
      relations: ['car'],
      where: { id },
    });

    const carStatus =
      params.order_status === '0' // 待处理状态
        ? '0'
        : params.order_status === '1' // 处理中
        ? '1'
        : params.order_status === '2' // 已完成
        ? '2'
        : params.order_status === '3' // 已结束
        ? '0'
        : '0';

    const updateCar = order.car;
    updateCar.status = carStatus;

    try {
      await this.orderRepository.update(id, params);
      await this.carRepository.save(updateCar);
    } catch (err) {
      return {
        code: '901',
        msg: '修改失败',
      };
    }
    return {
      code: '900',
      msg: 'success',
    };
  }

  // 删除订单
  remove(ids: number[]) {
    ids.forEach(async (id) => {
      try {
        await this.orderRepository
          .createQueryBuilder()
          .update(Order)
          .set({
            isDelete: true,
          })
          .where('id = :id', { id: id })
          .execute();
      } catch (e) {
        console.log('🚀 ~ This is a result of console.log ~ ✨: 删除失败', id);
      }
    });
    return;
  }
}
